#!/bin/sh

if [ -z "${HOMER}" ]; then
  HOMER=${HOME}
  export DRONE_COMMIT_MESSAGE="dev test commit"
fi

inits(){
  resHome=".cix/res/flow"
  mkdir -p ${resHome}
  targetFile="${resHome}/config.yaml"
  if [[ -f ${targetFile} ]]; then
      bkName="config.yaml.$(date "+%Y-%m-%d_%H-%M-%S")"
      cp ${targetFile} ${resHome}/${bkName}
      echo "back ${targetFile} to ${resHome}/${bkName}"
    fi
  cat  .cix/templates/config.yaml > ${targetFile}
}

clean(){
  rm -rf .cix/build
}

#新建一个模块，拷贝主模块文件到指定目录，并创建资源文件
newMod() {
  modName=$1
  modSrc=$2
  if test -z "${modName}" ; then
    echo "modName is null ,please use cix <modName> <modSrc>"
    exit 1
  fi
  if test -z "${modSrc}" ; then
    echo "modSrc is null ,please use cix <modName> <modSrc>"
    exit 1
  fi
  mkdir -p ${modSrc}
  files=("Makefile" "entrypoint.sh" "Dockerfile")
  for varFile in ${files[*]}; do
    theFilePath=${modSrc}/${varFile}
    #backup
    if [[ -f ${theFilePath} ]]; then
      bkName="${varFile}.$(date "+%Y-%m-%d_%H-%M-%S")"
      cp ${theFilePath} ${modSrc}/${bkName}
      echo "back ${theFilePath} to ${modSrc}/${bkName}"
    fi
    if [ -f ./${varFile} ]; then
      cat ./${varFile} > ${theFilePath}
      sed -i "s/\/flow/\/${modName}/g" ${theFilePath}
    fi
  done
  if [[ ! -d .cix/res/${modName} ]]; then
    mkdir -p .cix/res/${modName}
    cat .cix/templates/config.yaml > .cix/res/${modName}/config.yaml
  fi
}

Main(){
  export ciVersion=v1
  make -f .cix/mod.${ciVersion}.mk -f .cix/Makefile.${ciVersion}.mk $@
}

case "$1" in
'inits')
  shift
  inits $@
  ;;
'newMod')
  shift
  newMod $@
  ;;
'clean')
  shift
  clean $@
  ;;
*)
  Main $@
  ;;
esac